<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/8/20
 * Time: 13:21
 */
class Login extends MY_Controller
{


    public function __construct()
    {

        parent::__construct();

        //登录成功之后  已存在会话  则跳转主页
        $this->loadHelper("url");
        if(!empty($this->session("user")))
            $this->redirect(web_url("home/index",true));
    }


    //登录界面  和登录处理
    public function index()
    {

        $this->loadHelper(["url","form"]);
        $this->loadLibrary("form_validation");
        $error_message = "";

        if($this->isGet())  //get请求
        {
            $this->loadView(ADMIN . "login/login_index",compact('error_message'));
        }
        else
        {
            try
            {
                //获取数据
                $user_name = $this->post("user_name");
                $pass_word = $this->post("password");
                //校验规则
                $this->form_validation->set_error_delimiters('','\\');
                if($this->form_validation->run()===FALSE)
                {
                    throw new Exception(validation_errors());
                }
                else
                {
                    $this->loadModel("user");

                    //查询用户密码

                    $db_users = $this->user->getWhere(["user_name"=>$user_name]);

                    if(empty($db_users))
                    {
                        throw new Exception("用户不存在!");
                    }
                    $user = reset($db_users);

                    if(md5($pass_word)==$user->pass_word)//登录成功
                    {

                        //存储session
                         $this->session("user",$user);
                         //存储ip信息到Session
                         $login_ip = $this->input->ip_address();
                         $this->session("ip",$login_ip);
                         $ip_info = $this->get_ip_info($login_ip);

                         $db_ip_info = null;
                         if($ip_info)
                         {
                             $this->session("ip_info", $ip_info);
                             $db_ip_info = $ip_info['country'].'/'.$ip_info['city'].'/'.$ip_info['isp'];
                         }else
                             $db_ip_info = "未知ip";

                        //开始记录操作日志

                        $this->loadModel("usereventinfo");

                        $login_event_info =
                        [
                            'ip_addr'=>$login_ip,
                            'login_address'=>$db_ip_info,
                            'ctime'=>$this->time(),
                            'event_name'=>UserEventInfo::EVENT_LOGIN,
                            'user_id'=>$user->id
                        ];
                         $event_log_result =  $this->usereventinfo->add($login_event_info);

                         //登录成功跳转主页
                         if($event_log_result)
                         {
                             $this->redirect(web_url('home/index',true));
                         }
                         else
                         {
                             throw new Exception("登录未知错误!");
                         }

                    }
                    else
                    {
                        throw new Exception("密码错误!");
                    }
                }

            }
            catch(Exception $e)
            {
                $error_message = $e->getMessage();
                $this->loadView(ADMIN . "login/login_index",compact('error_message'));
            }

        }


    }


    //注册界面 和注册用户处理
    public function register()
    {
        $this->loadHelper(["url","form"]);
        $this->loadLibrary("form_validation");
        $error_message = "";
        //get请求
        if($this->isGet())
        {
            $this->loadView(ADMIN . "login/login_register",compact('error_message'));
        }else
        {  //处理post请求  用户注册

            //获取数据
            $user_name = $this->post("user_name");
            $pass_word = $this->post("password");
            //校验规则
            $this->form_validation->set_error_delimiters('','\\');
            if($this->form_validation->run()===FALSE)
            {
                throw new Exception(validation_errors());
            }
            else
            {
                //查询用户密码
                try
                {
                    $this->loadModel("user");

                    $db_users = $this->user->getWhere(["user_name" => $user_name]);

                    if (!empty($db_users))
                        throw new Exception("用户已存在!");

                    //用户不存在  则注册用户
                    $md5_pass_word = md5($pass_word);
                    $grant_code = substr($md5_pass_word, 0, 5);
                    $create_time = $this->time();
                    $new_user = [
                        'user_name' => $user_name,
                        'pass_word' => $md5_pass_word,
                        'grant_code' => $grant_code,
                        'ctime' => $create_time
                    ];

                    $add_result = $this->user->add($new_user);

                    //注册成功则跳转登录界面
                    if ($add_result) {

                        //往个人信息插入一些默认数据

                        $this->loadModel("userinfo");

                        $user_info =
                        [
                          'id'=>$add_result,  //最后插入的id
                          'nick_name'=>$user_name,
                          'user_email'=>$user_name
                        ];

                        $add_info_result = $this->userinfo->add($user_info);

                        if($add_info_result)
                        {

                            $this->redirect(web_url('login', true));
                        }
                        else
                        {
                            throw new Exception("注册失败!服务器开小猜了~");
                        }


                    } else {
                        throw new Exception("注册失败!服务器开小猜了~");
                    }

                }catch(Exception $e)
                {
                    $error_message = $e->getMessage();
                    $this->loadView(ADMIN . "login/login_register",compact('error_message'));
                }
            }


        }
    }


    //校验邮箱验证码
   public function check_email_code($email_code)
   {

       if($email_code=="test")
       {
           return true;
       }
       else
       {
           $this->form_validation->set_message("check_email_code","{field}不正确!");
           return false;
       }

   }


    //校验图片验证码
    public function check_img_code($email_code)
    {

        if($email_code=="test")
        {
            return true;
        }
        else
        {
            $this->form_validation->set_message("check_img_code","{field}不正确!");
            return false;
        }

    }


}